<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网络云运维日报故障处理上报系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .section {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .section h2 {
            margin-top: 0;
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f8f9fa;
        }
        .bottom-section {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 20px;
        }
        .log-box {
            flex: 1;
            min-width: 300px;
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .description-box {
            flex: 1;
            min-width: 300px;
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .buttons-container {
            width: 100%;
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }
        .buttons {
            display: flex;
            gap: 10px;
            justify-content: center;
            flex-wrap: wrap;
        }
        button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        textarea {
            width: 100%;
            height: 150px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
            font-family: monospace;
        }
        .log-text {
            width: 100%;
            height: 200px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
            font-family: monospace;
            background-color: #f8f9fa;
            overflow-y: auto;
        }
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 15px;
            gap: 10px;
        }
        .pagination button {
            padding: 5px 10px;
            background-color: #f8f9fa;
            color: #333;
            border: 1px solid #ddd;
        }
        .pagination button:hover {
            background-color: #e9ecef;
        }
        .pagination button.active {
            background-color: #007bff;
            color: white;
        }
        .pagination button:disabled {
            background-color: #f8f9fa;
            color: #6c757d;
            cursor: not-allowed;
        }
        .pagination-info {
            font-size: 14px;
            color: #666;
        }
        @media (max-width: 768px) {
            .bottom-section {
                flex-direction: column;
            }
            .log-box, .description-box {
                min-width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>网络云运维日报故障处理上报系统</h1>
        </div>
        
        <div class="section">
            <h2>故障处理明细</h2>
            <table id="fault-details-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>序号</th>
                        <th>故障设备名称</th>
                        <th>所属资源池</th>
                        <th>所属期次</th>
                        <th>故障发生时间</th>
                        <th>告警清除时间</th>
                        <th>设备归属类别</th>
                        <th>设备厂家</th>
                        <th>板件种类</th>
                        <th>发现方式</th>
                        <th>解决记录</th>
                        <th>是否国产</th>
                        <th>故障板件SN号</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 数据将通过JavaScript动态填充 -->
                </tbody>
            </table>
            <div class="pagination" id="fault-details-pagination">
                <!-- 分页控件将通过JavaScript动态填充 -->
            </div>
        </div>
        
        <div class="section">
            <h2>故障数量统计明细</h2>
            <table id="fault-counts-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>所属期次</th>
                        <th>硬件资源池名称</th>
                        <th>软集厂家</th>
                        <th>故障处理次数</th>
                        <th>创建时间</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 数据将通过JavaScript动态填充 -->
                </tbody>
            </table>
            <div class="pagination" id="fault-counts-pagination">
                <!-- 分页控件将通过JavaScript动态填充 -->
            </div>
        </div>
        
        <div class="section">
            <h2>故障厂家数统计明细</h2>
            <div style="max-height: 400px; overflow-y: auto;">
                <table id="manufacturer-stats-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>厂家</th>
                            <th>设备类型</th>
                            <th>光模块</th>
                            <th>CPU非国产</th>
                            <th>CPU国产(海光x86)</th>
                            <th>CPU国产(ARM)</th>
                            <th>内存</th>
                            <th>硬盘非国产</th>
                            <th>硬盘国产</th>
                            <th>缓存盘</th>
                            <th>背板</th>
                            <th>网卡非国产</th>
                            <th>网卡国产</th>
                            <th>传感器</th>
                            <th>RISER卡</th>
                            <th>PCIE卡非国产</th>
                            <th>PCIE卡国产</th>
                            <th>主板</th>
                            <th>电源</th>
                            <th>raid卡非国产</th>
                            <th>raid卡国产</th>
                            <th>尾纤</th>
                            <th>风扇非国产</th>
                            <th>风扇国产</th>
                            <th>整机</th>
                            <th>总数</th>
                            <th>创建时间</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 数据将通过JavaScript动态填充 -->
                    </tbody>
                </table>
            </div>
            <div class="pagination" id="manufacturer-stats-pagination">
                <!-- 分页控件将通过JavaScript动态填充 -->
            </div>
        </div>
        
        <div class="bottom-section">
            <div class="description-box">
                <h2>详细故障描述</h2>
                <textarea id="fault-description" readonly></textarea>
            </div>
            
            <div class="description-box">
                <h2>邮件发送日志</h2>
                <textarea id="email-log" readonly></textarea>
            </div>
        </div>
        
        <div class="buttons-container">
            <div class="buttons">
                <button onclick="processFaultData()">执行故障处理（先清空现有数据并重置自增ID）</button>
                <button onclick="sendReportEmail()">发送邮件报告</button>
                <button onclick="refreshData()">刷新数据</button>
                <button onclick="clearEmailLogs()">清除邮件日志</button>
            </div>
        </div>
    </div>

    <script>
        // 基础URL - 修改为绝对路径
        const BASE_URL = 'http://localhost:8000/api';
        
        // 当前页码状态
        const paginationState = {
            faultDetails: { page: 1, pageSize: 7 },
            faultCounts: { page: 1, pageSize: 10 },
            manufacturerStats: { page: 1, pageSize: 5 }
        };
        
        // 页面加载时获取数据
        document.addEventListener('DOMContentLoaded', function() {
            refreshData();
        });
        
        // 刷新所有数据
        function refreshData(includeSystemLogs = true) {
            getFaultDetails();
            getFaultCounts();
            getManufacturerStats();
            getFaultDescription();

            // 根据参数决定是否获取邮件日志
            // 当 includeSystemLogs 为 true 时，调用 getEmailLogs 函数更新日志显示区域
            if (includeSystemLogs) {
                getEmailLogs(); // 获取并显示最新的邮件日志
            }
        }
        
        // 获取故障明细
        async function getFaultDetails(page = 1) {
            try {
                paginationState.faultDetails.page = page;
                const { page: pageNum, pageSize } = paginationState.faultDetails;
                
                const response = await fetch(`${BASE_URL}/faults/details?page=${pageNum}&page_size=${pageSize}`);
                const result = await response.json();
                const { data, pagination } = result;
                
                const tableBody = document.querySelector('#fault-details-table tbody');
                tableBody.innerHTML = '';
                
                data.forEach(fault => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${fault.id}</td>
                        <td>${fault.serial_number || ''}</td>
                        <td>${fault.device_name || ''}</td>
                        <td>${fault.resource_pool || ''}</td>
                        <td>${fault.phase || ''}</td>
                        <td>${fault.fault_time || ''}</td>
                        <td>${fault.alarm_clear_time || ''}</td>
                        <td>${fault.device_category || ''}</td>
                        <td>${fault.manufacturer || ''}</td>
                        <td>${fault.component_type || ''}</td>
                        <td>${fault.discovery_method || ''}</td>
                        <td>${fault.solution_record || ''}</td>
                        <td>${fault.is_domestic || ''}</td>
                        <td>${fault.component_sn || ''}</td>
                    `;
                    tableBody.appendChild(row);
                });
                
                // 更新分页控件
                renderPagination('fault-details', pagination, getFaultDetails);
            } catch (error) {
                console.error('获取故障明细失败:', error);
            }
        }
        
        // 获取故障数量统计
        async function getFaultCounts(page = 1) {
            try {
                paginationState.faultCounts.page = page;
                const { page: pageNum, pageSize } = paginationState.faultCounts;
                
                const response = await fetch(`${BASE_URL}/faults/counts?page=${pageNum}&page_size=${pageSize}`);
                const result = await response.json();
                const { data, pagination } = result;
                
                const tableBody = document.querySelector('#fault-counts-table tbody');
                tableBody.innerHTML = '';
                
                data.forEach(count => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${count.id}</td>
                        <td>${count.phase || ''}</td>
                        <td>${count.hardware_resource_pool || ''}</td>
                        <td>${count.software_manufacturer || ''}</td>
                        <td>${count.fault_handling_count || 0}</td>
                        <td>${count.created_at || ''}</td>
                    `;
                    tableBody.appendChild(row);
                });
                
                // 更新分页控件
                renderPagination('fault-counts', pagination, getFaultCounts);
            } catch (error) {
                console.error('获取故障数量统计失败:', error);
            }
        }
        
        // 获取厂家故障统计
        async function getManufacturerStats(page = 1) {
            try {
                paginationState.manufacturerStats.page = page;
                const { page: pageNum, pageSize } = paginationState.manufacturerStats;
                
                const response = await fetch(`${BASE_URL}/faults/manufacturers?page=${pageNum}&page_size=${pageSize}`);
                const result = await response.json();
                const { data, pagination } = result;
                
                const tableBody = document.querySelector('#manufacturer-stats-table tbody');
                tableBody.innerHTML = '';
                
                data.forEach(stat => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${stat.id}</td>
                        <td>${stat.manufacturer || ''}</td>
                        <td>${stat.device_type || ''}</td>
                        <td>${stat.optical_module || 0}</td>
                        <td>${stat.cpu_non_domestic || 0}</td>
                        <td>${stat.cpu_domestic_hygon || 0}</td>
                        <td>${stat.cpu_domestic_arm || 0}</td>
                        <td>${stat.memory || 0}</td>
                        <td>${stat.disk_non_domestic || 0}</td>
                        <td>${stat.disk_domestic || 0}</td>
                        <td>${stat.cache_disk || 0}</td>
                        <td>${stat.backplane || 0}</td>
                        <td>${stat.nic_non_domestic || 0}</td>
                        <td>${stat.nic_domestic || 0}</td>
                        <td>${stat.sensor || 0}</td>
                        <td>${stat.riser_card || 0}</td>
                        <td>${stat.pcie_card_non_domestic || 0}</td>
                        <td>${stat.pcie_card_domestic || 0}</td>
                        <td>${stat.motherboard || 0}</td>
                        <td>${stat.power_supply || 0}</td>
                        <td>${stat.raid_card_non_domestic || 0}</td>
                        <td>${stat.raid_card_domestic || 0}</td>
                        <td>${stat.fiber || 0}</td>
                        <td>${stat.fan_non_domestic || 0}</td>
                        <td>${stat.fan_domestic || 0}</td>
                        <td>${stat.whole_machine || 0}</td>
                        <td>${stat.total_count || 0}</td>
                        <td>${stat.created_at || ''}</td>
                    `;
                    tableBody.appendChild(row);
                });
                
                // 更新分页控件
                renderPagination('manufacturer-stats', pagination, getManufacturerStats);
            } catch (error) {
                console.error('获取厂家故障统计失败:', error);
            }
        }
        
        // 渲染分页控件
        function renderPagination(elementPrefix, pagination, fetchDataFunction) {
            const { page, pages, total, page_size: pageSize } = pagination;
            const paginationContainer = document.getElementById(`${elementPrefix}-pagination`);
            
            // 清空分页控件
            paginationContainer.innerHTML = '';
            
            // 显示分页信息
            const infoDiv = document.createElement('div');
            infoDiv.className = 'pagination-info';
            infoDiv.textContent = `共 ${total} 条记录，第 ${page} 页，共 ${pages} 页`;
            paginationContainer.appendChild(infoDiv);
            
            // 创建分页按钮
            const buttonsDiv = document.createElement('div');
            buttonsDiv.className = 'pagination';
            
            // 首页按钮
            const firstButton = document.createElement('button');
            firstButton.textContent = '首页';
            firstButton.disabled = page === 1;
            firstButton.onclick = () => fetchDataFunction(1);
            buttonsDiv.appendChild(firstButton);
            
            // 上一页按钮
            const prevButton = document.createElement('button');
            prevButton.textContent = '上一页';
            prevButton.disabled = page === 1;
            prevButton.onclick = () => fetchDataFunction(page - 1);
            buttonsDiv.appendChild(prevButton);
            
            // 页码按钮（显示当前页前后各2页）
            const startPage = Math.max(1, page - 2);
            const endPage = Math.min(pages, page + 2);
            
            for (let i = startPage; i <= endPage; i++) {
                const pageButton = document.createElement('button');
                pageButton.textContent = i;
                pageButton.classList.toggle('active', i === page);
                pageButton.onclick = () => fetchDataFunction(i);
                buttonsDiv.appendChild(pageButton);
            }
            
            // 下一页按钮
            const nextButton = document.createElement('button');
            nextButton.textContent = '下一页';
            nextButton.disabled = page === pages || pages === 0;
            nextButton.onclick = () => fetchDataFunction(page + 1);
            buttonsDiv.appendChild(nextButton);
            
            // 末页按钮
            const lastButton = document.createElement('button');
            lastButton.textContent = '末页';
            lastButton.disabled = page === pages || pages === 0;
            lastButton.onclick = () => fetchDataFunction(pages);
            buttonsDiv.appendChild(lastButton);
            
            paginationContainer.appendChild(buttonsDiv);
        }
        
        // 获取详细故障描述
        async function getFaultDescription() {
            try {
                const response = await fetch(`${BASE_URL}/faults/description`);
                const data = await response.json();
                
                document.getElementById('fault-description').value = data.description || "暂无详细故障描述";
            } catch (error) {
                console.error('获取详细故障描述失败:', error);
                document.getElementById('fault-description').value = "获取详细故障描述失败";
            }
        }
        
        // 处理故障数据-按钮
        async function processFaultData() {
            try {
                addEmailLog("开始执行故障处理...", "INFO");
                const response = await fetch(`${BASE_URL}/faults/process`, {
                    method: 'POST'
                });
                const data = await response.json();
                
                if (data.message) {
                    addEmailLog(`故障处理完成: ${data.message}`, "INFO");
                    alert(data.message);
                    // 处理完成后刷新数据，但不刷新邮件日志
                    refreshData(false);
                }
            } catch (error) {
                console.error('处理故障数据失败:', error);
                addEmailLog(`处理故障数据失败: ${error.message}`, "ERROR");
                alert('处理故障数据失败: ' + error.message);
            }
        }
        
        // 发送报告邮件
        async function sendReportEmail() {
            try {
                addEmailLog("开始发送邮件报告...", "INFO");
                
                // 获取当前月份的文件名
                const now = new Date();

                // 获取当前月份并格式化为两位数字符串
                // now.getMonth() 返回 0-11 的数字，0 表示一月，11 表示十二月
                // 因此需要 +1 来得到实际月份（1-12）
                // .toString() 将数字转换为字符串
                // .padStart(2, '0') 确保月份为两位数，不足两位时前面补 0（例如 "1" 变为 "01"）
                let currentMonth = (now.getMonth() + 1).toString().padStart(2, '0');
                let currentYear = now.getFullYear();

               
                // 月份减一 ，确保使用上个月的文件
                /*
                let month = parseInt(currentMonth) - 1;
                // 处理1月减一的情况（变为上一年的12月）
                if (month === 0) {
                    month = 12;
                    // 年份也需要减一
                    currentYear = currentYear - 1;
                }
                currentMonth =  month.toString().padStart(2, '0');
                */

                
                const fileName = `网络云运维日报故障处理上报${currentYear}年${currentMonth}月-陕西省.xlsx`;
                
                const emailData = {
                    sender_email: "sxlibo@sn.chinamobile.com",
                    sender_password: "CF68BF8FA9F155C08B00",
                    recipients: ["zhangshuang01@ln.chinamobile.com"],
                    cc_recipients: ["libaolei@chinamobile.com"],
                    input_file: fileName
                };
                
                addEmailLog("准备发送邮件到: " + emailData.recipients.join(", "));
                addEmailLog("抄送: " + emailData.cc_recipients.join(", "));
                addEmailLog("附件: " + emailData.input_file);
                
                const response = await fetch(`${BASE_URL}/email/send-report`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(emailData)
                });
                
                const data = await response.json();
                
                if (data.status === "success") {
                    addEmailLog("邮件发送成功！", "INFO");
                    alert("邮件发送成功！");
                } else {
                    addEmailLog(`邮件发送失败: ${data.message}`, "ERROR");
                    alert("邮件发送失败: " + data.message);
                }
            } catch (error) {
                console.error('发送邮件失败:', error);
                addEmailLog(`发送邮件失败: ${error.message}`, "ERROR");
                alert('发送邮件失败: ' + error.message);
            }
        }
        
        // 获取邮件日志
        async function getEmailLogs() {
            try {
                const response = await fetch(`${BASE_URL}/logs/logs`);
                const data = await response.json();
                
                const logElement = document.getElementById('email-log');
                let logContent = '';
                
                // 显示最新的日志条目（按时间倒序排列）
                data.forEach(log => {
                    logContent += `[${log.created_at}] [${log.level}] ${log.message}\n`;
                });
                
                logElement.value = logContent;
                // 滚动到底部
                logElement.scrollTop = logElement.scrollHeight;
            } catch (error) {
                console.error('获取邮件日志失败:', error);
                document.getElementById('email-log').value = "获取邮件日志失败";
            }
        }
        
        // 添加邮件日志
        function addEmailLog(message, level = "INFO") {
            // 添加日志到textarea
            const logElement = document.getElementById('email-log');
            const timestamp = new Date().toLocaleString();
            const logEntry = `[${timestamp}] [${level}] ${message}\n`;
            logElement.value += logEntry;
            // 滚动到底部
            logElement.scrollTop = logElement.scrollHeight;
            
            // 同时向后端添加日志
            fetch(`${BASE_URL}/logs/logs`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `message=${encodeURIComponent(message)}&level=${encodeURIComponent(level)}`
            }).catch(error => {
                console.error('添加邮件日志失败:', error);
            });
        }
        
        // 清除邮件日志
        async function clearEmailLogs() {
            if (confirm("确定要清除所有邮件日志吗？此操作不可恢复。")) {
                try {
                    const response = await fetch(`${BASE_URL}/logs/logs`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        // 清空日志显示区域
                        document.getElementById('email-log').value = '';
                        addEmailLog("邮件日志已清空", "INFO");
                    } else {
                        const errorData = await response.json();
                        addEmailLog(`清除日志失败: ${errorData.message}`, "ERROR");
                    }
                } catch (error) {
                    console.error('清除邮件日志失败:', error);
                    addEmailLog(`清除日志失败: ${error.message}`, "ERROR");
                }
            }
        }
    </script>
</body>
</html>